﻿$(document).ready(function () {
    var text = $("#Text");

    var toggle = $('<br /><input type="checkbox" id="toggle-auto-ingredients" checked="checked" />' +
                   '<label for="toggle-auto-ingredients">Automatic suggestions</label>');

    var ingredients = $("#recipeIngredients");
    var wasEdited = $.trim(ingredients.val()) != "";
    ingredients.focus(function () {
        wasEdited = true;
    });
    ingredients.after(toggle);
    $("#toggle-auto-ingredients").click(function () {
        if ($(this).attr("checked"))
            wasEdited = false;
    });

    var runner = function () {
        if ($("#toggle-auto-ingredients").attr("checked")) {
            if (!wasEdited) {
                var currentText = text.val();

                var suggestions = [];
                var lines = currentText.split(/[\r\n]/);
                for (var i = 0; i < lines.length; i++) {
                    var recipeLine = /^(\d+([,.]\d+)?[ ]?\w+)[ ]+([\wñåäöéèêæøÑÅÄÖÉÈÊÆØ]{2,}( [\wñåäöéèêæøÑÅÄÖÉÈÊÆØ]{2,})?)$/i;
                    var results = recipeLine.exec(lines[i]);
                    if (results != null)
                        suggestions.push(RegExp.$3);
                }
                ingredients.val(suggestions.join(", "));
            } else if ($.trim(currentIngredients) === "")
                wasEdited = false;
        }

        setTimeout(runner, 2000);
    };

    runner();
});